package com.cicv.oss.config.infra.config.util;

import lombok.SneakyThrows;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

public class MyFileUtil {

    public static String read(String path) {
        return read(new File(path));
    }

    public static String read(File file) {
        try {
            return read(Files.newInputStream(file.toPath()), 4096);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String read(InputStream inputStream) {
        return read(inputStream, 4096);
    }

    public static String read(File file, int bufferLength) {
        try {
            return read(Files.newInputStream(file.toPath()), bufferLength);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String read(InputStream inputStream, int bufferLength) {
        try {
            StringBuilder result = new StringBuilder();
            byte[] buf = new byte[bufferLength];//创建字节数组，存储临时读取的数据
            int len;//记录数据读取的长度
            //循环读取数据
            while ((len = inputStream.read(buf)) != -1) { //长度为-1则读取完毕
                result.append(new String(buf, 0, len)).append("\n");
            }
            inputStream.close();
            return result.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
